package main

import (
    "fmt"
    "io/ioutil"
    "net/http"
    "html/template"
    "launchpad.net/mgo/bson"
    "launchpad.net/mgo"
)

type ebook struct {
    Name string
    Author []string
}

var c *mgo.Collection
var t = template.Must(template.ParseFiles("./html/show.html"))

func main() {
    session, err := mgo.Dial("localhost")
    if err != nil {
        panic(err)
    }
    defer session.Close()

    session.SetMode(mgo.Monotonic, true)

    c = session.DB("book").C("bookfi")

    http.HandleFunc("/", indexHandler)
    http.HandleFunc("/search/", searchHandler)
    http.ListenAndServe(":8080", nil)
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    b, e := ioutil.ReadFile("html/index.html")
    if e != nil {
        fmt.Println("read error!")
    }
    w.Write(b)
}

func searchHandler(w http.ResponseWriter, r *http.Request) {
    keyword := r.FormValue("keyword")
    books := []ebook{}
    c.Find(bson.M{"name": bson.RegEx{keyword, "i"}}).All(&books)
    t.Execute(w, books)
}
